package com.acme.concurrent.indexer;

import java.io.File;
import java.util.concurrent.BlockingQueue;

/**
 * @author Gregory Sobko
 */
class FileIndexer implements Runnable {
    private final BlockingQueue<File> queue;
    private final FileQueuePool fileQueuePool;
    private final int index;
    private int indexed = 0;
    private int stolen = 0;


    public FileIndexer(FileQueuePool fileQueuePool, int i) {
        queue = fileQueuePool.getQueue(i);
        this.fileQueuePool = fileQueuePool;
        index = i;
    }

    public void run() {
        try {
            while (true){
                File file = queue.poll();
                if(file == null){
                    file = fileQueuePool.trySteal(index);
                    if(file != null){
                        stolen++;
                    }
                }
                if(file == null){
                    file = queue.take();
                }
                if(file == FileQueuePool.POISONOUS_PILL){
                    return;
                }
                indexFile(file);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }finally {
            System.out.println("Indexer#" + index + " Indexed: " + indexed + " stolen: " + stolen);
        }
    }

    public void indexFile(File file){
        indexed++;
    }
}

